package utils

import (
	"a-common/config"
	"errors"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

// 密钥
// var stSigning = "abc"

type JwtClaims struct {
	ID     int64
	Name   string
	Device string
	Tenant int64
	Roule  []string
	jwt.RegisteredClaims
}

// CreateToken 创建令牌
func CreateToken(id int64, subject, name, device, ip string, ttl time.Duration) (string, error) {
	nowTime := time.Now()
	iJwtClaims := JwtClaims{
		ID:     id,
		Name:   name,
		Device: device,
		RegisteredClaims: jwt.RegisteredClaims{
			// 主题
			Subject: subject,
			// 发行者
			Issuer: "aijuan",
			// 签发时间
			IssuedAt: jwt.NewNumericDate(nowTime),
			// 过期时间
			ExpiresAt: jwt.NewNumericDate(nowTime.Add(ttl)),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, iJwtClaims)

	// 加密 密钥+IP地址，防止滥用token
	return token.SignedString([]byte(config.Config.Login.Token.Salt + ip))
}

// ParseToken 解析令牌
func ParseToken(token, ip string) (*JwtClaims, error) {
	cla, err := jwt.ParseWithClaims(token, &JwtClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(config.Config.Login.Token.Salt + ip), nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := cla.Claims.(*JwtClaims); ok && cla.Valid {
		return claims, nil
	}
	return nil, errors.New("invalid token")
}
